<template>
  <view class="container">
    <!-- 全选按钮 -->
    <view class="select-all">
      <checkbox :value="selectAll" @change="toggleSelectAll" class="checkbox"></checkbox>
      <text>全选</text>
    </view>

    <!-- 商品信息展示区域 -->
    <view v-for="(order, index) in ordersList" :key="index" class="shop-item">
      <view class="status-text">等待买家付款……</view>
      <view class="good">
        <checkbox :value="order.selected" @change="toggleSelection(index, $event)" class="checkbox"></checkbox>
        <image :src="order.images" mode="aspectFill" class="shop-img"></image>
        <view class="shop-text">
          <view class="order-info">
            <view class="order-id">订单号：{{ order.orderId }}</view>
            <view class="order-price">￥{{ (order.orderPrice * order.orderCount).toFixed(2) }}</view>
          </view>
          <view class="order-name">{{ order.orderName }}</view>
        </view>
        <view class="order-quantity">
          X {{ order.orderCount }}
        </view>
      </view>
      <view class="button-group">
        <button class="buy" @click="continuePayment(order)">继续付款</button>
        <button class="cancel" @click="cancelOrder(order)">取消订单</button>
      </view>
    </view>

    <!-- 未找到订单提示 -->
    <view v-if="ordersList.length === 0" class="shop-else-list">
      没有找到状态为0的订单。
    </view>

    <!-- 底部总价和结算按钮 -->
    <view class="shop-foot" v-if="ordersList.length > 0">
      <view class="foot-total">
        总价: <text class="foot-count">￥{{ totalAmount.toFixed(2) }}</text>
      </view>
      <button class="foot-num" @click="settleAccounts">去结算</button>
    </view>
  </view>
</template>

<script>
import config from '@/config.js'

export default {
  data() {
    return {
      ordersList: [],
      selectAll: false
    }
  },
  computed: {
    totalAmount() {
      return this.ordersList.reduce((sum, order) => {
        if (order.selected) {
          return sum + (parseFloat(order.orderPrice) * parseInt(order.orderCount));
        }
        return sum;
      }, 0);
    }
  },
  methods: {
    fetchOrdersByState() {
      uni.request({
        url: `${config.apiUrl}/order/state/0`,
        method: 'GET',
        success: (response) => {
          if (response.data && response.data.length > 0) {
            this.ordersList = response.data.map(order => ({ ...order, selected: false }));
          } else {
            uni.showToast({
              title: '没有找到状态为0的订单',
              icon: 'none'
            });
          }
        },
        fail: (error) => {
          console.error('获取订单信息请求失败', error);
          uni.showToast({
            title: '请求失败，请重试',
            icon: 'none'
          });
        }
      });
    },
    toggleSelection(index, event) {
      this.ordersList[index].selected = event.detail.value;
      this.selectAll = this.ordersList.every(order => order.selected);
    },
    toggleSelectAll(event) {
      const newValue = event.detail.value;
      this.selectAll = newValue;
      this.ordersList.forEach(order => {
        order.selected = newValue;
      });
    },
    continuePayment(order) {
      // 更新订单状态为1
      console.log("继续付款按钮被点击");

      const updatedOrder = {
        ...order,
        orderState: 1
      };

      // 发送请求到后端，更新订单状态
      uni.request({
        url: `${config.apiUrl}/order/updateOrderStateWeb`, // 确保这里的API URL是正确的
        method: "POST", // 使用POST方法来发送请求
        header: {
          "Content-Type": "application/json" // 设置请求头为JSON格式
        },
        data: updatedOrder, // 将订单数据发送到后端
        success: (response) => {
          if (response.statusCode === 200) {
            uni.showToast({
              title: "成功继续付款",
              icon: "success"
            });
            // 更新订单列表
            this.fetchOrdersByState();
            this.$forceUpdate(); // 强制更新
          } else {
            uni.showToast({
              title: "继续付款失败",
              icon: "none"
            });
          }
        },
        fail: (error) => {
          // 处理请求失败的情况
          console.error("继续付款请求失败", error);
          uni.showToast({
            title: "请求失败，请重试",
            icon: "none"
          });
        }
      });
    },
    cancelOrder(order) {
      console.log("取消订单被点击");
	  const updatedOrder = {
	      ...order,
	      orderState: -1
	    };
	  
	    // 发送请求到后端，更新订单状态
	    uni.request({
	      url: `${config.apiUrl}/order/updateOrderStateWeb`, // 确保这里的API URL是正确的
	      method: "POST", // 使用POST方法来发送请求
	      header: {
	        "Content-Type": "application/json" // 设置请求头为JSON格式
	      },
	      data: updatedOrder, // 将订单数据发送到后端
	      success: (response) => {
	        if (response.statusCode === 200) {
	          uni.showToast({
	            title: "成功取消订单",
	            icon: "success"
	          });
	          // 更新订单列表
	          this.fetchOrdersByState();
	          this.$forceUpdate(); // 强制更新
	        } else {
	          uni.showToast({
	            title: "取消订单失败",
	            icon: "none"
	          });
	        }
	      },
	      fail: (error) => {
	        // 处理请求失败的情况
	        console.error("取消订单请求失败", error);
	        uni.showToast({
	          title: "请求失败，请重试",
	          icon: "none"
	        });
	      }
	    });
	  
    },
    settleAccounts() {
      const selectedOrders = this.ordersList.filter(order => order.selected);

      if (selectedOrders.length === 0) {
        uni.showToast({
          title: "请选择至少一个订单",
          icon: "none"
        });
        return;
      }

      // 更新选中的订单状态为1
      console.log("去结算按钮被点击");

      uni.request({
        url: `${config.apiUrl}/order/updateOrderStateWeb`,
        method: "POST",
        header: {
          "Content-Type": "application/json"
        },
        data: selectedOrders.map(order => ({ ...order, orderState: 1 })),  // 将订单状态设为1，并批量更新
        success: (response) => {
          if (response.statusCode === 200) {
            uni.showToast({
              title: "成功结算",
              icon: "success"
            });
            // 更新订单列表
            this.fetchOrdersByState();
            this.$forceUpdate(); // 强制更新
          } else {
            uni.showToast({
              title: "结算失败",
              icon: "none"
            });
          }
        },
        fail: (error) => {
          console.error("结算请求失败", error);
          uni.showToast({
            title: "请求失败，请重试",
            icon: "none"
          });
        }
      });
    }
  },
  created() {
    this.fetchOrdersByState();
  }
}
</script>

<style>
.shop-list {
  padding-bottom: 100rpx;
  background-color: #ffffff;
  height: 100%;
}

.select-all {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 15rpx;
}

.checkbox {
  margin-right: 20rpx;
}

.shop-else-list {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: #ffffff;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 18rpx;
}

.shop-item {
  display: flex;
  flex-direction: column;
  padding: 30rpx;
  background-color: #f5f5f5;
  margin: 20rpx 0;
  border-radius: 15rpx;
  position: relative; /* 新增此行以便能够绝对定位状态文本 */
}

.status-text {
  position: absolute;
  top: -15rpx;
  right: 30rpx;
  color: #ff6600;
  font-size: 16rpx;
}

.good {
  display: flex;
  align-items: center;
  margin-top: 15rpx;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15rpx;
}

.shop-img {
  width: 120rpx;
  height: 120rpx;
  margin-right: 20rpx;
  border-radius: 10rpx;
}

.shop-text {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.order-info {
  display: flex;
  justify-content: space-between;
}

.order-id {
  font-size: 18rpx;
  color: #333;
}

.order-price {
  font-size: 18rpx;
  color: #333;
}

.order-name {
  font-size: 20rpx;
  color: #333;
}

.order-quantity {
  text-align: right;
  font-size: 18rpx;
  color: #666;
}

.button-group {
  display: flex;
  gap: 10rpx;
  margin-top: 10rpx;
}

.buy {
  padding: 10rpx 25rpx;
  border: 1px solid #ff5400;
  background-color: #fff;
  color: #ff5400;
  border-radius: 5rpx;
  font-size: 16rpx;
  cursor: pointer;
}

.cancel {
  padding: 10rpx 25rpx;
  border: 1px solid #cccccc;
  background-color: #f5f5f5;
  color: #808080;
  border-radius: 5rpx;
  font-size: 16rpx;
  cursor: pointer;
}

.shop-foot {
  border-top: 1px solid #f7f7f7;
  background-color: #ffffff;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20rpx;
  box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
}

.foot-total {
  font-size: 20rpx;
  color: #333;
}

.foot-count {
  color: #ff5400;
  font-size: 20rpx;
  margin-left: 5rpx;
}

.foot-num {
  background-color: #ff5400;
  color: white;
  padding: 0 60rpx;
  height: 100rpx;
  line-height: 100rpx;
  border-radius: 5rpx;
  text-align: center;
  font-size: 20rpx;
  border: none;
  cursor: pointer;
}

</style>
